<?php
namespace app\houtai\controller;
use Exception;
use think\exception\PDOException;
use think\db\Expression;
use RuntimeException;
use org\ThinkActionIterator;

class CliController extends \think\Controller {
  
  protected function _initialize() {
    if (!IS_CLI) {
      throw new RuntimeException('This program can only be run in DOS mode.');
    }
  }
  
  // php index.php houtai/cli/online
  public function onlineAction(){
    var_dump(__METHOD__);
    $suffix = '.gg';
    $list = table('GameScoreLocker', "rydb.record{$suffix}")->query("
SELECT
	a.UserID,
	a.KindID,
	a.ServerID,
	b.GameID,
	b.NickName,
	b.Channel,
	c.HeadImgUrl AS Avatar,
	e.RoomCard,
	ISNULL(f.Score, 0) AS Score,
	ISNULL(f.InsureScore, 0) AS Insure,
	0 AS TableID,
	1 AS ChairID,
	0 AS State,
	0 AS GroupID,
	0 AS GroupIndex,
	0 AS Grade
FROM
	RYTreasureDB.dbo.GameScoreLocker AS a
LEFT JOIN RYAccountsDB.dbo.AccountsInfo b ON b.UserID = a.UserID
LEFT JOIN RYAccountsDB.dbo.IndividualDatum c ON c.UserID = a.UserID
LEFT JOIN RYPlatformDB.dbo.GameChannel d ON d.ID = b.Channel
LEFT JOIN RYTreasureDB.dbo.UserRoomCard e ON e.UserID = a.UserID
AND (
	e.KindID = CASE d.CustomID
	WHEN 1 THEN
		0
	ELSE
		a.KindID
	END
)
LEFT JOIN RYTreasureDB.dbo.GameScoreInfo f ON f.UserID = a.UserID
ORDER BY
	a.UserID
    ");
    echo(json_encode($list, JSON_UNESCAPED_UNICODE));
  }
  
  // php index.php houtai/cli/addrobotroomcard
  public function addrobotroomcardAction() {
    $RMVAL = 10000000;
    $suffix = '.hh';
    $KindList = [];
    $GameKindItem = table('GameKindItem', "rydb.platform{$suffix}")->where(['Nullity' => 0])->select();
    if (!empty($GameKindItem)) {
      foreach($GameKindItem as $row) {
        $KindList[$row['KindID']] = $row['KindName'];
      }
    }
    $listUser = table('AccountsInfo', "rydb.accounts{$suffix}")->query('
SELECT t.* FROM(
SELECT
	a.UserID,
	a.GameID,
	a.NickName,
	(SELECT COUNT(ID) FROM RYTreasureDB.dbo.UserRoomCard b WHERE b.UserID = a.UserID) AS ecx
FROM
	RYAccountsDB.dbo.AccountsInfo AS a
WHERE
	a.AccountsType = 3
) t WHERE ecx <> 11
    ');
    for($i = count($listUser) - 1; $i >= 0; $i--) {
      $user = $listUser[$i];
      printf("[%08d][%08d][%08d][%s]\n", $i, $user['UserID'], $user['GameID'], $user['NickName']);
      foreach($KindList as $KindID => $KindName) {
        $eax = table('AccountsGameCurrency', "rydb.basic{$suffix}")->where(['UserID' => $user['UserID'], 'KindID' => $KindID])->find();
        if (empty($eax)) {
          $eax = table('AccountsGameCurrency', "rydb.basic{$suffix}")->insert(['UserID' => $user['UserID'], 'KindID' => $KindID, 'RoomCard' => $RMVAL]);
        } else {
          $eax = table('AccountsGameCurrency', "rydb.basic{$suffix}")->where('ID', $eax['ID'])->setInc('RoomCard', $RMVAL);
        }
      }
      // break;
    }
  }
  // php index.php houtai/cli/bianlimvc
  public function bianlimvcAction() {
    var_dump(__METHOD__);

    $suffix = '.hh';
    $dir = dirname(__FILE__);
    $tai = new ThinkActionIterator;

    $files = $tai->BianLi_Controller($dir);
    $files = array_unique($files); // 移除重复&&排序
    var_dump($dir);
    for ($i = count($files) - 1; $i >= 0; $i--) {
      $file = $files[$i];
      $name = str_replace([$dir, '.php', '/'], ['app\houtai\controller', '', "\\"], $file);
      // printf("[%03d]%s\n", $i, $name);
      $actions = $tai->BianLi_Controller_Action($name);
      for ($j = count($actions) - 1; $j >= 0; $j--) {
        $action = $actions[$j];
        $url = preg_replace(['/^app\\\houtai\\\controller\\\/', '/Action$/', '/Controller::/', '/\\\/'], ['', '', '/', '.'], $action);
        $url = strtolower($url);
        echo("'{$url}',\n");
        // continue;
        $eax = table('Ky_AdminAction', "rydb.websms{$suffix}")->where(['LinkUrl' => $url])->count();
        if ($eax == 0) {
          $eax = table('Ky_AdminAction', "rydb.websms{$suffix}")->insert(['LinkUrl' => $url]);
        }
        
      }
    }
  }
  /**
   *  @brief  : 
   *  @return : 
   *  @details: php index.php houtai/cli/wxqqr
   */
  public function wxqqrAction(){
    foreach([
      3809519927,
    ] as $comment_id) {
      $eax = self::get_comment($comment_id);
    }
  }
  /**
   *  @brief  : 
   *  @return : 
   *  @details: php index.php houtai/cli/wxqq
   */
  public function wxqqAction() {
    var_dump(__METHOD__);
    for ($page = 0; $page < 1000; $page++) {
      // $url = "https://pacaio.match.qq.com/xw/getSiteHotEvent?ext=sports&num=30&page={$page}";
      // $url = "https://pacaio.match.qq.com/xw/getSiteHotEvent?ext=finance&num=30&page={$page}";
      // $url = "https://pacaio.match.qq.com/xw/getSiteHotEvent?ext=milite&num=30&page={$page}";
      // $url = "https://pacaio.match.qq.com/xw/getSiteHotEvent?ext=tech&num=30&page={$page}";
      // $url = "https://pacaio.match.qq.com/xw/getSiteHotEvent?ext=auto&num=30&page={$page}";
      // $url = "https://pacaio.match.qq.com/xw/getSiteHotEvent?ext=world&num=30&page={$page}";
      $url = "https://pacaio.match.qq.com/xw/getSiteHotEvent?ext=visit&num=20&page={$page}";
      var_dump($url);
      $list = file_get_contents($url);
      $list = json_decode($list, true);
      if ($list['code'] != 0) {
        throw new RuntimeException('读取推荐失败!');
      }
      $list = $list['data'];
      foreach($list as $item) {
        echo("[{$item['comment_id']}][{$item['title']}][{$item['comment_num']}]\n");
        continue;
        self::get_comment($item['comment_id']);
      }
    }

  }
  //
  protected static function get_comment($comment_id){
    $idx = 1;
    $cursor = '0';
    do {
      $url = "https://coral.qq.com/article/{$comment_id}/comment/v2?orinum=30&pageflag=1&cursor={$cursor}";
      $data = file_get_contents($url);
      $data = json_decode($data, true);
      if ($data['errCode'] != 0) {
        throw new RuntimeException('读取评论失败!');
      }
      $data = $data['data'];
      
      echo(json_encode([
        'now' => YmdHis(),
        'comment' => $comment_id,
        'cursor' => $cursor,
        'page' => $idx,
        'total' => count($data['userList']),
      ])."\n");

      foreach($data['userList'] as $user) {

        try {
          $eax = table('Robot', 'rydb.websms')->insert(['Nick' => $user['nick'], 'Gender' => $user['gender'], 'Region' => $user['region']]);
        } catch (Exception $e) {
          $error = $e->getMessage();
          $errno = $e->getCode();
          if (!(10501 == $errno && strpos($error, 'Violation of UNIQUE KEY constraint')!==false)) {
            trace("[{$errno}][{$error}]");
            throw $e;
          }
        }
        
        try {
          $eax = table('RobotAvatar', 'rydb.websms')->insert(['Head' => $user['head']]);
        } catch (Exception $e) {
          $error = $e->getMessage();
          $errno = $e->getCode();
          if (!(10501 == $errno && strpos($error, 'Violation of UNIQUE KEY constraint') !== false)) {
            trace("[{$errno}][{$error}]");
            throw $e;
          }
        }
        
      }
      if ($cursor == $data['last']) {
        var_dump('游标递归中断');
        break;
      }
      if (!$data['hasnext']) {
        var_dump('没有下页中断');
        break;
      }
      $cursor = $data['last'];
      $idx++;
    } while (true);
  }
  // php index.php houtai/cli/GetUserInfo
  public function GetUserInfoAction() {
    var_dump(__METHOD__);
    $conf = config('wxgzh.xngj');
    $wapi = new \wechat\Wechat($conf);
    $user = $wapi->GetUserInfo('ae86d97fac2d377de6df022717fa7521');
    var_dump($user);
    var_dump(['errno' => $wapi->errCode, 'error' => $wapi->errMsg]);
  }
  /**
   *  @brief  : 测试微信公众号企业付款到零钱功能
   *  @return : none
   *  @details: php index.php houtai/cli/CashPocket
   */
  public function CashPocketAction() {
    var_dump(__METHOD__);

    $conf = config("wxgzh.xxgj");
    var_dump($conf);
    
    $mapi = new \wechat\MchApi($conf);
    var_dump($mapi);

    $tradNo = $mapi::MakeTradeNo();
    var_dump($tradNo);

    $orde = $mapi->CashPocket([
      'openid'        => 'oSoOH1Be-_SUqRkeFAKrP-rTBerY',  // 'o-yqAvxS4Shxmfyz3-lcIRettm-g',
      'check_name'    => false, // 不强校验真实姓名
      'amount'        => 1, // 付款金额, 单位为分
      'desc'          => "小鲜肉, 恭喜发财!",
      'partner_trade_no' => $tradNo,
    ]);
    var_dump($orde);

    if ($orde['result_code'] == 'FAIL') { // 支付失败
      if ($orde['err_code'] == 'SYSTEMERROR') { // 系统繁忙
        // 支付失败&&系统繁忙, 查询订单确认
        $bill = $mapi->GetCashPocketTransferInfo($tradNo);
        if ($bill['result_code'] == 'FAIL') { // 支付失败&&查询失败
          return result([], 110, $bill['err_code_des']);
        } else { // 支付失败&&查询成功
          // SUCCESS:转账成功; FAILED:转账失败; PROCESSING:处理中
          if (!in_array($bill['status'], ['SUCCESS', 'PROCESSING'])) {
            return result([], 0, '转账失败, 请稍后再试!');
          }
        }
      } else {
        return result([], 111, $orde['err_code_des']);
      }
    }
  }

}
